from django import forms
from django.contrib.auth import authenticate
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from XinYuWIT.models import User, MentalHealth
import datetime


# Create your views here.
def homepage(request):
    """个人主页"""
    if request.method == "GET":
        info = request.session.get('info')
        user = User.objects.get(id=info.get('id'))
        if user.is_authenticated:
            end_date = datetime.date.today()
            start_date = end_date - datetime.timedelta(days=6)

            recent_records = MentalHealth.objects.filter(user=user, date__range=(start_date, end_date)).order_by('date')
            records_dict = {record.date: record.score for record in recent_records}

            date_format = "%Y-%m-%d"
            dates = tuple(start_date + datetime.timedelta(days=i) for i in range(7))
            scores = [records_dict.get(date, 0) for date in dates]
            dates_formated = [date.strftime(date_format) for date in dates]

            context = {
                "username": user.username,
                "registrationDate": user.created_at,
                "avatar": user.avatar,
                'chart_labels': dates_formated,
                'chart_data': scores,
            }

            return render(request, "homepage.html", context)
        else:
            return redirect("/login/")


class LoginForm(forms.Form):
    """登录表单"""
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput(
            attrs={
                'class': 'input-box',
                'placeholder': '用户名'
            }
        )
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(
            render_value=True,
            attrs={
                'class': 'input-box',
                'placeholder': '密码'
            }
        )
    )

class RegisterForm(UserCreationForm):
    """"注册表单"""
    class Meta:
        model = User
        fields = ["username", "password1", "password2"]
    username = forms.CharField(
        label='用户名',
        widget=forms.TextInput(
            attrs={
                'class': 'input-box',
                'placeholder': '用户名'
            }
        )
    )
    password1 = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(
            render_value=True,
            attrs={
                'class': 'input-box',
                'placeholder': '密码'
            }
        )
    )
    password2 = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(
            render_value=True,
            attrs={
                'class': 'input-box',
                'placeholder': '确认密码'
            }
        )
    )

class PersonalInfoForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["first_name", "last_name", "phone", "gender", "birthday", "mbti"]
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['placeholder'] = field.label


loginForm = LoginForm()
registerForm = RegisterForm()

def register(request):
    if request.method == "GET":
        return render(
            request,
            "login-registeration.html",
            {
                'loginForm': loginForm,
                'registerForm': registerForm,
                'show_register': True,
            }
        )
    elif request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            form.save()
        if not form.errors:
            form.add_error("password2","注册成功，请登录！")
        return render(
            request,
            "login-registeration.html",
            {
                'loginForm': loginForm,
                'registerForm': form,
                'show_register': True,
            }
        )

def login(request):
    """登录"""
    if request.method == "GET":
        return render(
            request,
            "login-registeration.html",
            {
                'loginForm': loginForm,
                'registerForm': registerForm,
                'show_register': False,
            }
        )
    elif request.method == "POST":
        form = LoginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username = username, password = password)

            if user is not None:
                request.session["info"] = {
                    'id': user.id,
                }
                return redirect('/home/')
            else:
                request.session.clear()
                form.add_error("password", "用户名或密码错误")
                return render(
                    request,
                    "login-registeration.html",
                    {
                        'loginForm': form,
                        'registerForm': registerForm,
                        'show_register': False,
                    }
                )
        else:
            return render(
                request,
                "login-registeration.html",
                {
                    'loginForm': form,
                    'registerForm': registerForm,
                    'show_register': False,
                }
            )



def logout(request):
    """注销"""
    request.session.clear()
    return redirect("/login/")


def home(request):
    return render(request, "main-page-yes.html", {})

def personal_center(request):
    info = request.session.get('info')
    user = User.objects.get(id=info.get('id'))
    if request.method == "GET":
        if user.is_authenticated:
            username = user.username
            gender = user.gender
            phone = user.phone
            birthday = user.birthday
            avatar = user.avatar
            mbti = user.mbti

            context = {
                'username': username,
                'gender': gender,
                'phone': phone,
                'birthday': birthday,
                'avatar': avatar,
                'mbti': mbti,

                'InfoForm': PersonalInfoForm(),
            }
            return render(request, "personalcenter.html", context)
    elif request.method == "POST":
        if user.is_authenticated:
            form = PersonalInfoForm(request.POST)
            if form.is_valid():
                gender = form.cleaned_data['gender']
                phone = form.cleaned_data['phone']
                birthday = form.cleaned_data['birthday']
                #avatar = form.cleaned_data['avatar']
                mbti = form.cleaned_data['mbti']
                user.gender = gender
                user.phone = phone
                user.birthday = birthday
                #user.avatar = avatar
                user.mbti = mbti
                user.save()

            if not form.errors:
                return redirect("/personalcenter/")
            else:
                return render(request, "personalcenter.html", {'InfoForm': form})




